package com.cop4331.social;

import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;

/**
 * 
 * @author Matt Szoke
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * Allows user to request an appointment with tutor
 * 
 */
public class RescheduleRequestActivity extends Activity {

	EditText date;
	EditText time;
	EditText location;
	EditText subject;
	EditText other;
	Button setDate;
	Button setTime;
	Button helpDate;
	Button helpTime;
	Button helpSub;
	Button helpLoc;
	Button helpOther;
	Button ok;
	Button cancel;
	TextView err;

	// For dialog switch statement
	// 0 means choose Date Dialog
	// 1 means choose Time Dialog
	static final int DATE_DIALOG_ID = 0;
	static final int TIME_DIALOG_ID = 1;

	static boolean validDate = false;

	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;

	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.scheduletutor);

		// User Input Fields - Match variables to XML (scheduletutor.xml)
		date = (EditText) findViewById(R.id.et_date);
		time = (EditText) findViewById(R.id.et_time);
		location = (EditText) findViewById(R.id.et_location);
		subject = (EditText) findViewById(R.id.et_subject);
		other = (EditText) findViewById(R.id.et_other);

		// Buttons - Set date/time buttons
		setDate = (Button) findViewById(R.id.b_date);
		setTime = (Button) findViewById(R.id.b_time);

		// Buttons -Used for dialogs
		helpDate = (Button) findViewById(R.id.help_date);
		helpTime = (Button) findViewById(R.id.help_time);
		helpSub = (Button) findViewById(R.id.help_subject);
		helpLoc = (Button) findViewById(R.id.help_location);
		helpOther = (Button) findViewById(R.id.help_other);

		ok = (Button) findViewById(R.id.b_ok);
		cancel = (Button) findViewById(R.id.b_cancel);

		// Error text view
		err = (TextView) findViewById(R.id.tv_err);

		// Retreive the username of the person using the app
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		HashMap<String, String> user = db.getUserDetails();
		final String un = user.get("name");

		// Retreive bundle from previous activity
		// Bundle contains tutor selected in ChooseTutorActivity
		Bundle b = getIntent().getExtras();
		final String tutor = b.getString("tutor");
		final String cname = b.getString("cname");
		final String id = b.getString("id");
		final String tutoree = b.getString("tutoree");
		final String type = b.getString("type");

		subject.setText(cname);

		subject.setEnabled(false);

		UserFunctions uf = new UserFunctions();

		// Add functionality to help date button
		helpDate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(RescheduleRequestActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("Choose Date Help: ");
				dialog.setCancelable(true);

				// Display help dialog to user
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("Use the set button to choose a date you would like to request for tutoring.\n\nBe sure to enter a valid date.");
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();

			}
		});

		// Add functionality to help time button
		helpTime.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(RescheduleRequestActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("Choose Time Help: ");
				dialog.setCancelable(true);

				// Display help dialog to user
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("Use the set button to choose a time you would like to request for tutoring.\n\nBe sure to enter a valid time.");
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();

			}
		});

		// Add functionality to help subject button
		helpSub.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(RescheduleRequestActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("Choose Topic Help: ");
				dialog.setCancelable(true);

				// Display help dialog to user
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("Please enter a topic for this session.\n\nBe sure to enter a relevant topic.");
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();

			}
		});

		// Add functionality to help location button
		helpLoc.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(RescheduleRequestActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("Choose Location Help: ");
				dialog.setCancelable(true);

				// Display help dialog to user
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("Please enter a meeting location for your tutoring session.\n\nBe sure to enter a convenient location.");
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();

			}
		});

		// Add functionality to help other button
		helpOther.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(RescheduleRequestActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("Other Help: ");
				dialog.setCancelable(true);

				// Display help dialog to user
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("This box is used for other important information you would like to relay to your potential tutor.");
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();

			}
		});

		// Add functionality to set - date button
		setDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

		// Add functionality to set - time button
		setTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});

		// Defaults values to current Day / month / year
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		// Defaults values to current hour / minute
		final Calendar t = Calendar.getInstance();
		mHour = t.get(Calendar.HOUR_OF_DAY);
		mMinute = t.get(Calendar.MINUTE);

		// Adds functionality to ok button
		ok.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				// Retreive input fields
				String dateStr = date.getText().toString();
				String timeStr = time.getText().toString();
				String subStr = subject.getText().toString();
				String otherStr = other.getText().toString();
				String locStr = location.getText().toString();

				// Date is invalid
				if (validDate == false) {
					err.setText("Please enter a valid date.");
				}
				// No date entered
				else if (dateStr.compareTo("") == 0) {
					err.setText("Please enter a date.");
				}
				// No time entered
				else if (timeStr.compareTo("") == 0) {
					err.setText("Please enter a time.");
				}
				// No topic entered
				else if (subStr.compareTo("") == 0) {
					err.setText("Please enter a topic.");
				}
				// No location entered
				else if (locStr.compareTo("") == 0) {
					err.setText("Please enter a location.");
				}
				// Everything is okay, attempt to add to database
				else {

					// Add session to database with 1 meaning PENDING - WAITING
					// FOR APPROVAL
					UserFunctions userFunction = new UserFunctions();

					System.out.println(type);

					String messageRep;

					if (un.compareTo(tutor) == 0)
						messageRep = tutoree;

					else
						messageRep = tutor;

					userFunction
							.addMessage(
									"CramSessions",
									messageRep,
									"Reschedule Request",
									un
											+ " has requested to reschedule a session with you.");

					userFunction.updateSessionInfo(id, tutor, tutoree, dateStr,
							timeStr, locStr, subStr, otherStr, type);

					Intent dashboard = new Intent(getApplicationContext(),
							DashBoardActivity.class);

					// Close all views before launching DashBoard
					dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(dashboard);

					// Close Login Screen
					finish();
				}
			}
		});

		// Add functionality to "cancel" button
		cancel.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// Return to dashboard
				Intent log = new Intent(getApplicationContext(),
						DashBoardActivity.class);
				startActivity(log);
				finish();

			}
		});
		
		// Title Bar Buttons
		ImageButton about, home, message;

		about = (ImageButton) findViewById(R.id.b_about);
		home = (ImageButton) findViewById(R.id.b_home);
		message = (ImageButton) findViewById(R.id.b_message);
		
		// Check for new messages
		JSONObject j_mess = uf.retreiveMessages(un, "new");

		try {
			if (Integer.parseInt(j_mess.getString("size")) > 0) {
				message.setVisibility(View.VISIBLE);
			} else
				message.setVisibility(View.GONE);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		// Button to show app info
		about.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(RescheduleRequestActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("CramSessions v 1.0 2012");
				dialog.setCancelable(true);

				// Create and show a dialog to help the user with this specific
				// field
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("CramSessions was created by:\n\n-Matt Szoke\n-Daniel Moody\n-Jeovanny Alvarez\n-Kia Manoochehri\n-Rj Anderson\n-Doug Wagner");
				text.setGravity(Gravity.LEFT);
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		});
		
		// Button to return to dashboard
		home.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						DashBoardActivity.class);
				startActivity(sa);
				finish();

			}
		});

		// Goto inbox if new message exists
		message.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						MessageNotifications.class);
				startActivity(sa);
				finish();

			}
		});
	}

	// -----------------------------------------------
	// MDATESETLISTENER
	// Launches dialog when date set button is choosen
	// -----------------------------------------------
	/**
	 * @uml.property name="mDateSetListener"
	 * @uml.associationEnd multiplicity="(1 1)"
	 */
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		// When the user sets a date
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;

			Calendar c = Calendar.getInstance();

			// Checks that the chosen year is beyond the current year
			if (mYear > c.get(Calendar.YEAR)) {
				err.setText("");
				ok.setEnabled(true);
				validDate = true;
			}

			// If we are on the current year, check to make sure the month is
			// past the current month
			else if ((mYear == c.get(Calendar.YEAR))
					&& (mMonth > c.get(Calendar.MONTH))) {
				err.setText("");
				ok.setEnabled(true);
				validDate = true;
			}

			// If we are on the current year and month, check to make sure the
			// day is on or past the current day
			else if ((mYear == c.get(Calendar.YEAR))
					&& (mMonth == c.get(Calendar.MONTH))
					&& (mDay >= c.get(Calendar.DAY_OF_MONTH))) {
				err.setText("");
				ok.setEnabled(true);
				validDate = true;
			} else {

				// Date is invalid, disable continue button and prompt user with
				// error
				ok.setEnabled(false);
				err.setText("Please enter a valid date.");
			}

			mMonth = mMonth + 1;

			String monthHolder = Integer.toString((mMonth));
			String dayHolder = Integer.toString(mDay);

			if (monthHolder.length() == 1)
				monthHolder = "0" + monthHolder;

			if (dayHolder.length() == 1)
				dayHolder = "0" + dayHolder;

			// Set the text field to the selected date
			date.setText("" + monthHolder + "/" + dayHolder + "/" + mYear);
		}
	};

	// -----------------------------------------------
	// MTIMESETLISTENER
	// Launches dialog when date set button is choosen
	// -----------------------------------------------
	/**
	 * @uml.property name="mTimeSetListener"
	 * @uml.associationEnd multiplicity="(1 1)"
	 */
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		// When the user sets a time
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;

			String tempHour;
			String tempMinute;

			// If the time is 0 military, set it to 12 for 12 AM
			if (mHour == 0) {
				mHour = 12;
			}

			// If the military time is greater than 12, -12 and set string to PM
			if (mHour > 12) {
				mHour = mHour - 12;

				tempHour = Integer.toString(mHour);
				tempMinute = Integer.toString(mMinute);

				if (tempHour.length() == 1)
					tempHour = "0" + tempHour;

				if (tempMinute.length() == 1)
					tempMinute = "0" + tempMinute;

				time.setText(tempHour + ":" + tempMinute + " PM");
			}

			// Set string to AM
			else {
				tempHour = Integer.toString(mHour);
				tempMinute = Integer.toString(mMinute);

				if (tempHour.length() == 1)
					tempHour = "0" + tempHour;

				if (tempMinute.length() == 1)
					tempMinute = "0" + tempMinute;

				time.setText(tempHour + ":" + tempMinute + " AM");
			}
		}
	};

	// -----------------------------------------------
	// ONCREATEDIALOG
	// Whenever a dialog option is created, chooses which one to launch
	// -----------------------------------------------
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);

		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
					true);
		}
		return null;
	}
}
